package net.entelijan.cobean.table;

public class BeanTreatingFactory {
	
	private static IBeanTreater treater = null;

	private BeanTreatingFactory() {
		super();
	}

	/**
	 * Creates a bean treater from the system property
	 * 'net.entelijan.cobean.BeanTreaterClass' or if this property or creates a
	 * 'net.entelijan.cobean.table.SimpleBeanTreater' if the property is
	 * not set.
	 * 
	 * @return
	 */
	public static IBeanTreater createTreater() {
		if (treater == null) {
			treater = createNewTreater();
		}
		return treater;
	}

	private static IBeanTreater createNewTreater() {
		IBeanTreater re;
		String className = System
				.getProperty("net.entelijan.cobean.BeanTreaterClass");
		if (className != null) {
			re = createTreaterFromClassName(className);
		} else if (isLoadable("net.entelijan.cobean.bind.impl.SpringBeanTreater")) {
			re = createTreaterFromClassName("net.entelijan.cobean.bind.impl.SpringBeanTreater");
		} else {
			re = createTreaterFromClassName("net.entelijan.cobean.table.SimpleBeanTreater");
		}
		return re;
	}

	private static boolean isLoadable(String className) {
		try {
			Class.forName(className, true, BeanTreatingFactory.class.getClassLoader());
			return true;
		} catch (ClassNotFoundException e) {
			return false;
		}
	}

	private static IBeanTreater createTreaterFromClassName(String className) {
		try {
			return (IBeanTreater) Class.forName(className).newInstance();
		} catch (Exception e) {
			throw new IllegalStateException("Could not instantiate '"
					+ className + "'. " + e.getMessage());
		}
	}

}
